package com.yungam.exception.handler;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.yungam.common.response.RetDTO;
import com.yungam.exception.bean.BusinessException;
import com.yungam.exception.bean.ErrorCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 业务异常
     *
     * @param e 异常
     * @return 异常结果
     */
    @ExceptionHandler(BusinessException.class)
    public RetDTO<?> handleBusinessException(BusinessException e) {
        log.error("BusinessException", e);
        String msg = e.getMessage();
        if (StringUtils.isNotBlank(e.getDescription())) msg += ", 错误描述: " + e.getDescription();
        return RetDTO.error(msg);
    }

    /**
     * 业务异常
     *
     * @param e 异常
     * @return 异常结果
     */
    @ExceptionHandler(NullPointerException.class)
    public RetDTO<?> handleNullPointerException(NullPointerException e) {
        log.error("发生控制针异常, 错误信息为", e);
        String msg = e.getMessage();
        log.error("=========>{}", msg);
        return RetDTO.error(msg);
    }

    /**
     * 运行时异常
     *
     * @param e 异常
     * @return 异常结果
     */
    @ExceptionHandler(RuntimeException.class)
    public RetDTO<?> handleRuntimeException(HttpServletRequest request, RuntimeException e) {
        log.error("RuntimeException {}", e.getMessage());
        log.error("RuntimeException Url {}", request.getRequestURL());
        return RetDTO.error(ErrorCodeEnum.SYSTEM_ERROR.getMessage());
    }
}
